package com.hyou.starter.autoconfigure.datasource.hikari;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hyou.starter.autoconfigure.datasource.MyDataSource;

/**
 * 数据源配置。
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-05-21 11:29:51 初始创建
 */
@Configuration
@ConditionalOnClass(com.zaxxer.hikari.HikariDataSource.class)
@ConditionalOnProperty(prefix = "hyou.datasource", name = "hikari", matchIfMissing = true)
public class HikariDataSourceAutoConfiguration {
    
    private static final Logger log = LoggerFactory.getLogger(HikariDataSourceAutoConfiguration.class);
    
    /**
     * @return 数据源配置属性数据对象
     */
    @Bean
    @ConfigurationProperties(prefix = "hyou.datasource.hikari")
    public HikariDataSourceMapProp hikariDataSourceMapProp() {
        return new HikariDataSourceMapProp();
    }
    
    /**
     * @return 默认数据源
     */
    @Bean
    public String defaultDataSource() {
        return hikariDataSourceMapProp().getDefaultDataSource();
    }
    
    @Bean
    public MyDataSource configDataSource(@Qualifier("hikariDataSourceMapProp") HikariDataSourceMapProp dsMapProp) {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        for(Entry<String, HikariDataSourceProp> entry : dsMapProp.getDataSourceMap().entrySet()){
            dataSourceMap.put(entry.getKey(), HikariDataSourceUtil.makeDataSource(entry.getValue()));
        }
        log.info("dsMapProp : {}", dsMapProp);
        log.info("dataSourceMap : {}", dataSourceMap);
        return new MyDataSource(dataSourceMap, dsMapProp.getDefaultDataSource());
    }
    
}
